<?php

namespace app\common\library;

use alipay\aop\AopClient;
use alipay\aop\request\AlipayTradeRefundRequest;
use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Kernel\Factory;
use app\common\model\MoneyLog;
use app\common\model\order\Order;
use app\common\model\User;
use stdClass;
use think\Env;
use wechatPay\Wxpay;

/**
 * 统一退款
 */
class Refund
{
    //退款
    public static function refund($id, $refund_money)
    {

        $out_refund_no=sn('order', 'out_refund_no', 'RF');
        //商户订单号,微信生成的退款订单号 二选一即可
        $order = Order::get($id);
        if (Env::get('app.debug') == true) {
            $refund_money = 0.01;
        }
        $time = time();
        $refundData = [
            'out_refund_no' => $out_refund_no,
            'reason' => '商品退款',

            'notify_url' =>  cdnurl('/api/notify/refundNotify', true), //需根据自己的情况修改回调接口，也可以为空
            'funds_account' => 'AVAILABLE',
            'amount' => [
                'refund' => floatval($refund_money) * 100, //退款标价金额，单位为分，可以做部分退款
                'total' => floatval($refund_money) * 100, //订单总金额，单位为分
                'currency' => 'CNY'
            ]
        ];

        $refundData['transaction_id'] = $order['transaction_id'];
        $url = 'https://api.mch.weixin.qq.com/v3/refund/domestic/refunds';
        $urlarr = parse_url($url); //拆解为：[scheme=>https,host=>api.mch.weixin.qq.com,path=>/v3/pay/transactions/native]
        $mchid = config('site.mch_id'); //商户ID
        $xlid = config('site.serial_no'); //证书序列号

        $refundData = json_encode($refundData);
        $nonce = Wxpay::getNonceStr();
        $key = Wxpay::getSign($refundData, $urlarr['path'], $nonce, $time);
        $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"', $mchid, $xlid, $nonce, $time, $key);
        $header  = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'User-Agent:*/*',
            'Authorization: WECHATPAY2-SHA256-RSA2048 ' . $token
        );
        $res = Wxpay::curl_post_https($url, $refundData, $header);
        $res_array = json_decode($res, true);
        if (isset($res_array['status']) && ($res_array['status'] == 'PROCESSING' || $res_array['status'] == 'SUCCESS') && isset($res_array['status'])) {
            return true;
        } else {
            exception($res_array['message']);
        }
    }

    //退款
    public static function aliRefund($refund_money, $out_refund_no)
    {

        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->signType = 'RSA2'; //env('ALIPAY_SIGN_TYPE');

        $options->appId = config('site.alipay_appid');



        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        $options->merchantPrivateKey = config('site.alipay_private_key');

        // $options->alipayCertPath = '<-- 请填写您的支付宝公钥证书文件路径，例如：/foo/alipayCertPublicKey_RSA2.crt -->';
        // $options->alipayRootCertPath = '<-- 请填写您的支付宝根证书文件路径，例如：/foo/alipayRootCert.crt" -->';
        // $options->merchantCertPath = '<-- 请填写您的应用公钥证书文件路径，例如：/foo/appCertPublicKey_2019051064521003.crt -->';

        // $options->alipayCertPath = base_path('data/cert') . '/alipayCertPublicKey_RSA2.crt';
        // $options->alipayRootCertPath = base_path('data/cert') . '/alipayRootCert.crt';
        // $options->merchantCertPath = base_path('data/cert') . '/appCertPublicKey_2021002147645197.crt';

        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        $options->alipayPublicKey = config('site.alipay_public_key');

        //可设置异步通知接收服务地址（可选）
        $options->notifyUrl = cdnurl('/api/notify/alipayNotify', true);

        //可设置AES密钥，调用AES加解密相关接口时需要（可选）
        // $options->encryptKey = "<-- 请填写您的AES密钥，例如：aa4BtZ4tspm2wnXLb1ThQA== -->";
        Factory::setOptions($options);
        // $this->options = $options;

        try {
            //2. 发起API调用（以支付能力下的统一收单交易创建接口为例）
            $result = Factory::payment()->common()->refund($out_refund_no, $refund_money);
            if (!empty($result->code) && $result->code == 10000) {
                $order = Order::get(['sn' => $out_refund_no]);
                $user = User::get($order->user_id);
              
                //扣除可分红金额
                if ($user->use_dividend <= $order->dividend) {
                    $user->use_dividend = 0;
                } else {
                    $user->setDec('use_dividend', $order->dividend);
                }
                //扣除合计分红金额
                if ($user->total_dividend <= $order->dividend) {
                    $user->total_dividend = 0;
                } else {
                    $user->setDec('total_dividend', $order->dividend);
                }
                //权益值扣除
                if ($order->interests > 0) {
                    if ($user->total_interests <= $order->interests) {
                        $user->setDec('total_interests', $user->total_interests);
                    } else {
                        $user->setDec('total_interests', $order->interests);
                    }
                }
                //返回等级
                if ($order->group_id > 0) {
                    $group_id = Order::whereNotIn('id', $order->id)->where('user_id', $order->user_id)->where('group_id', '>', 0)->whereIn('status', ['1', '2', '3', '4'])->order('group_id desc')->value('group_id');
                    if (!$group_id) {
                        $group_id = 1;
                        $user->grouptime = 0;
                    }
                    $user->group_id = $group_id;
                }
                //上级累计权益值扣除
                if ($order->p_id > 0) {
                    $puser = User::get($order->p_id);
                    if ($order->p_interests >= $puser->total_interests) {
                        $puser->total_interests = 0;
                        $puser->save();
                    } else {
                        $puser->setDec('total_interests', $order->p_interests);
                    }
                }
                Refund::unify_refund($refund_money, $order->sn);
                $order->save();
                $user->save();
            } else {
                exception("调用失败，原因：" . $result->msg . "，" . $result->subMsg . PHP_EOL);
            }
        } catch (\Exception $e) {
            exception("调用失败，" . $e->getMessage() . PHP_EOL);
        }
        return true;



        // $aop = new AopClient();

        // $object['out_refund_no'] = $out_refund_no;
        // $object['refund_amount'] = $refund_money;
        // //// 返回参数选项，按需传入
        // //$queryOptions =[
        // //   'refund_detail_item_list'
        // //];
        // //$object->query_options = $queryOptions;
        // $json = json_encode($object);
        // $request = new AlipayTradeRefundRequest();

        // $request->setBizContent($json);

        // $result = $aop->execute($request);
        // $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        // $resultCode = $result->$responseNode->code;
        // $out_trade_no = $result->$responseNode->out_trade_no;
        // $out_trade_no = $result->$responseNode->out_trade_no;
        // if (!empty($resultCode) && $resultCode == 10000) {
        //     $order = Order::get(['out_refund_no' => $out_trade_no]);
        //     if ($order->p_id) {
        //         $puser = User::get($order->p_id);
        //         if ($puser->total_interests <= $order->p_interests) {
        //             $puser->total_interests = 0;
        //         } else {
        //             $puser->setDec('total_interests', $order->p_interests);
        //         }
        //     }
        //     if ($order->dividend > 0) {
        //         if ($user->use_dividend <= $order->dividend) {
        //             $user->use_dividend = 0;
        //         } else {
        //             $user->setDec('use_dividend', $order->dividend);
        //         }
        //     }
        //     if ($order->interests > 0) {
        //         if ($user->total_interests <= $order->interests) {
        //             $user->total_interests = 0;
        //         } else {
        //             $user->setDec('total_interests', $order->interests);
        //         }
        //     }
        //     if ($order->pay_money > 0) {
        //         $user->setDec('consumption', $order->pay_money);
        //     }
        //     if ($order->group_id > 0) {
        //         $group_id = Order::whereNotIn('id', $order->id)->where('user_id', $order->user_id)->where('group_id', '>', 0)->whereIn('status', ['1', '2', '3', '4'])->order('group_id desc')->value('group_id');
        //         if (!$group_id) {
        //             $group_id = 1;
        //             $user->grouptime = 0;
        //         }
        //         $user->group_id = $group_id;
        //     }
        //     // if ($order->interests > 0) {
        //     //     if ($order->interests >= $user->use_dividend) {
        //     //         $order->refund_interests = $user->use_dividend;
        //     //     }
        //     //     if ($order->interests < $user->use_dividend) {
        //     //         $order->refund_interests = $order->interests;
        //     //     }
        //     //     $user->use_dividend = $order->refund_interests;

        //     // }
        //     $order->save();
        //     $user->save();
        //     $puser->save();

        //     return true;
        // } else {
        //     exception('失败');
        // }
    }
    public static function unify_refund($refund_money, $out_refund_no)
    {
        $order = Order::get(['sn' => $out_refund_no]);
        $user = User::get($order->user_id);
        //上级累计权益值扣除
        if ($order->p_id) {
            $puser = User::get($order->p_id);
            if ($puser->total_interests <= $order->p_interests) {
                $puser->total_interests = 0;
                $user->save();
            } else {
                $puser->setDec('total_interests', $order->p_interests);
            }
        }
        if ($order->dividend > 0) {
            //扣除可分红金额
            if ($user->use_dividend <= $order->dividend) {
                $user->setDec('use_dividend', $user->use_dividend);
            } else {
                $user->setDec('use_dividend', $order->dividend);
            }
            //扣除合计分红金额
            if ($user->total_dividend <= $order->dividend) {
                $user->setDec('total_dividend', $user->total_dividend);
            } else {
                $user->setDec('total_dividend', $order->dividend);
            }
        }
        //权益值扣除
        if ($order->interests > 0) {
            if ($user->total_interests <= $order->interests) {
                $user->setDec('total_interests', $user->total_interests);
            } else {
                $user->setDec('total_interests', $order->interests);
            }
        }


        if ($order->pay_money > 0) {
            $user->setDec('consumption', $order->pay_money);
        }
        if ($order->group_id > 0) {
            $group_id = Order::whereNotIn('id', $order->id)->where('user_id', $order->user_id)->where('group_id', '>', 0)->whereIn('status', ['1', '2', '3', '4'])->order('group_id desc')->value('group_id');
            if (!$group_id) {
                $group_id = 1;
                $user->grouptime = 0;
            }
            $user->group_id = $group_id;
        }
        $data = MoneyLog::get(['order_sn' => $out_refund_no]);

        if ($data) {
            if ($data['source_type'] == 503) {
                MoneyLog::income($user->id, $refund_money, 2, 506, $out_refund_no);
            } elseif ($data['source_type'] == 504) {
                MoneyLog::income($user->id, $refund_money, 2, 505, $out_refund_no);
            }
        }
        $data = [
            'status' => '6',
            'returntime' => time(),
            'refund_price' => $refund_money,
            'out_refund_no' => sn('order', 'out_refund_no', 'RF')
        ];
        $order->status = '6';
        $order->returntime = time();
        $order->refund_price = $refund_money;
        $order->out_refund_no = $out_refund_no;
        $order->allowField(true)->save($data);
        $user->save();
        return true;
    }
}
